mysql union查询,每个union上有单独的别名

xyhw6mcr  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(550)

我正在创建一个搜索查询mysql,使用 UNION 要连接多个表,现在的问题是添加别名来标识每个表,因为如果添加带有别名的表名,则会显示错误 COLUMN NOT FOUND 我试图在每个联合表上添加别名,但遇到了错误,我不知道该怎么做才能将其写入。有人能帮我吗。
查询

SELECT * FROM (
    (
        SELECT 'food' as type,
        food_id AS item_id,
        food_name AS item_name,
        primary_image AS item_img,
        food_price AS item_price,
        food_currency AS item_currency,
        food_discount AS item_discount,
        chef_status AS ison
        FROM foods
    ) AS f

    UNION

    (
        SELECT 'chef' as type,
        chef_pagename AS item_id,
        business_name AS item_name,
        chef_photo AS item_img,
        NULL AS item_price,
        NULL AS item_currency,
        NULL AS item_discount,
        chef_status AS ison
        FROM our_chefs
    ) AS c
) AS fsc

WHERE f.food_name LIKE '%chicken%'
OR f.item_price LIKE '%100%'
OR c.business_name LIKE '%chicken%'
AND fsc.ison = 1

谢谢你们的贡献,我现在已经解决了这个问题

WHERE item_name LIKE '%chicken%'
OR item_price LIKE '%100%'
AND fsc.ison = 1
gzjq41n4

gzjq41n41#

我想这就是你想要的:

SELECT * FROM (

  (
    SELECT 'food' as type,
    food_id AS item_id,
    food_name AS item_name,
    primary_image AS item_img,
    food_price AS item_price,
    food_currency AS item_currency,
    food_discount AS item_discount,
    chef_status AS ison
    FROM foods
    WHERE food_name LIKE '%chicken%'
    OR item_price LIKE '%100%'
  )  

  UNION

  (
    SELECT 'chef' as type,
    chef_pagename AS item_id,
    business_name AS item_name,
    chef_photo AS item_img,
    NULL AS item_price,
    NULL AS item_currency,
    NULL AS item_discount,
    chef_status AS ison
    FROM our_chefs
    WHERE business_name LIKE '%chicken%'
  )  
) AS a

WHERE  a.ison = 1

相关问题