如果主键与第3个表匹配并按第3个表排序,我将如何连接2个表?

时间:2012-03-15 01:11:53

标签: mysql select join sql-order-by union

如果它们与第三个表的主键匹配,我正在尝试连接具有相同结构的两个表。然后我想根据第3个表中的列进行排序。

示例结构:

 Table 1 - id (VARCHAR) | title (VARCHAR) | expire (TIMESTAMP)

 Table 2 - id (VARCHAR) | title (VARCHAR) | expire (TIMESTAMP)

 Table 3 - id (VARCHAR) | views (VARCHAR) | expire (TIMESTAMP)

我认为这应该有效,但事实并非如此:

 SELECT * FROM table1 as t, table3 as t3 WHERE t.id = t3.id
 UNION
 SELECT * FROM table2 as t2, table3 as t3 WHERE t2.id = t3.id
 ORDER BY table3.expire DESC

有什么可以做到这一点?

4 个答案:

答案 0 :(得分:2)

使用JOIN将表3中的排序列放入,然后对其进行排序。

SELECT table_1.*, table_3.expire as t3_expire
  FROM table_1
  INNER JOIN table_3 on table_1.id = table_3.id
UNION ALL
SELECT table_2.*, table_3.expire
  FROM table_2
  INNER JOIN table_3 on table_2.id = table_3.id
ORDER BY t3_expire DESC;

答案 1 :(得分:0)

一旦你有一个联盟,数据就无法区分了。所以你应该试试

 SELECT * FROM table1 as t, table3 as t3 WHERE t.id = t3.id
 UNION
 SELECT * FROM table2 as t2, table3 as t3 WHERE t2.id = t3.id
 ORDER BY expire DESC

这和你要问的一样好。 除非你真的想到别的东西,否则你应该多分享一下。

答案 2 :(得分:0)

你的意思是这样的吗?

SELECT 
    t.id AS t_id, t.title AS t_title, 
    t2.id AS t2_id, t2.title AS t2_title, 
    t3.expire 
FROM table3 AS t3
LEFT JOIN table1 as t ON t3.id = t.id
LEFT JOIN table2 as t2 ON t3.id = t2.id
ORDER BY t3.expire DESC

答案 3 :(得分:0)

SELECT *
FROM Table3
  LEFT JOIN Table1 ON Table3.id = Table1.id
  LEFT JOIN Table2 ON Table3.id = Table2.id
WHERE
  Table1.id IS NOT NULL AND Table2.id IS NOT NULL
ORDER BY Table3.expire DESC