且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在MySQL中合并多个查询结果(按列)

更新时间:2022-11-27 18:45:24

您能做的***的是UNION或UNION ALL,但这要求它们具有相同的类型和列数.例如:

The best you can do is a UNION or UNION ALL but this requires them to have the same type and number of columns. For example:

SELECT 'Customer' AS type, id, name FROM customer
UNION ALL
SELECT 'Supplier', id, name FROM supplier
UNION ALL
SELECT 'Employee', id, full_name FROM employee

列名不必匹配.第一部分的别名将用于其余部分.

The column names don't have to match. The aliases from the first part will be used for the rest.

我还将添加它,而不是:

I'll also add that instead of:

select cls.* from (calls as cls inner join calls_users as clsusr on cls.id=clsusr.call_id) inner join users as usr on usr.id=cls.assigned_user_id where cls.assigned_user_id='seed_max_id'

您应该删除不必要的子查询,然后执行以下操作:

you should remove the unnecessary subquery and just do:

SELECT c.*
FROM calls c
JOIN calls_users cu ONc.id = cu.call_id
WHERE c.assigned_user_id = 'seed_max_id'

不需要额外的复杂性,并且上面的内容明显更具可读性.

There's no need for the extra complexity and the above is eminently more readable.