mysql-SQL:合并结果

SELECT * FROM `restaurants` WHERE name LIKE '%string%'

SELECT * FROM `restaurants` WHERE address LIKE '%string%'

SELECT * FROM `menu_items` WHERE name LIKE '%string%'

我有这些疑问.

目前,我分别显示每个查询结果.我想将它们全部结合起来.

并且所有结果都应使用别名来自何处.
例如,当它显示来自menu_items的项目/行时,您应该能够在“类型”列中看到它是“项目”.

餐馆地址结果的“地址”和餐馆名称结果的“名称”.

在MySQL中

我怎样才能做到这一点?

我的最终输出应如下所示:您在“ s”之后搜索

Spagetti - item
Sonus Suni - restaurant
Sunssisway 1232 - restaurant address
Delicous Spaga - item

所以我需要创建自己的别名列..’item’AS’Type’等.

最佳答案
如果要合并具有不同列的表,则必须指定所需的列.

SELECT
    'Name' AS Type,
    Id AS R_Id,
    NULL AS I_Id,
    Name,
    Address,
    NULL AS M_Id
FROM Restaurants
WHERE Name LIKE '%string%'
UNION ALL
SELECT
    'Address' AS Type,
    Id AS R_Id,
    NULL AS I_Id,
    Name,
    Address,
    NULL AS M_Id
FROM Restaurants
WHERE Address LIKE '%string%'
UNION ALL
SELECT
    'Item' AS Type,
    NULL AS R_Id,
    Id AS I_Id,
    Name,
    NULL AS Address,
    M_Id
FROM Menu_Items
WHERE Name LIKE '%string%'

转载注明原文:mysql-SQL:合并结果 - 代码日志