查询3个表,最后一个表有一个额外的行要查找 试过这个:
(SELECT 't1' AS tn, navid, clicks AS cc, tags
FROM t1
WHERE DATE_ADD(d, INTERVAL '0 8' DAY_HOUR) <= NOW()
AND tags LIKE '%cars%' )
UNION DISTINCT
(SELECT 't2' AS tn, navid, clicks AS cc, tags
FROM t2
WHERE DATE_ADD(d, INTERVAL '0 8' DAY_HOUR) <= NOW()
AND tags LIKE '%cars%' )
UNION DISTINCT
(SELECT 't3' AS tn, navid, title, clicks AS cc, tags
FROM t3
WHERE DATE_ADD(d, INTERVAL '0 8' DAY_HOUR) <= NOW()
AND tags LIKE '%cars%' )
我想在t3中获得title
字段
任何帮助,谢谢
答案 0 :(得分:2)
只需将它添加到前两个子查询中,其值为NULL:
(SELECT 't1' AS tn, navid, NULL as title, clicks AS cc, tags
FROM t1
WHERE DATE_ADD(d, INTERVAL '0 8' DAY_HOUR) <= NOW()
AND tags LIKE '%cars%' )
UNION DISTINCT
(SELECT 't2' AS tn, navid, NULL as title, clicks AS cc, tags
FROM t2
WHERE DATE_ADD(d, INTERVAL '0 8' DAY_HOUR) <= NOW()
AND tags LIKE '%cars%' )
UNION DISTINCT
(SELECT 't3' AS tn, navid, title, clicks AS cc, tags
FROM t3
WHERE DATE_ADD(d, INTERVAL '0 8' DAY_HOUR) <= NOW()
AND tags LIKE '%cars%' )
答案 1 :(得分:1)
由UNION组合的SQL应具有相同的列数和类型。
这是因为您只有一个查询结果,即使它看起来像多个小查询。
因此,您必须为title
列添加一些值。您在t1
和t2
中没有它。所以只需选择null
:
SELECT 't1' AS tn, navid, null as title, clicks AS cc, tags
...
(SELECT 't1' AS tn, navid, null as title, clicks AS cc, tags
FROM t1
WHERE DATE_ADD(d, INTERVAL '0 8' DAY_HOUR) <= NOW()
AND tags LIKE '%cars%' )
UNION DISTINCT
(SELECT 't2' AS tn, navid, null as title, clicks AS cc, tags
FROM t2
WHERE DATE_ADD(d, INTERVAL '0 8' DAY_HOUR) <= NOW()
AND tags LIKE '%cars%' )
UNION DISTINCT
(SELECT 't3' AS tn, navid, title, clicks AS cc, tags
FROM t3
WHERE DATE_ADD(d, INTERVAL '0 8' DAY_HOUR) <= NOW()
AND tags LIKE '%cars%' )
答案 2 :(得分:1)
您必须为UNION提供相同数量的列,并且列名称基于第一个查询,因此您无需为UNION中的每个查询命名列
(SELECT 't1' AS tn, navid, '' As title, clicks AS cc, tags
FROM t1
WHERE DATE_ADD(d, INTERVAL '0 8' DAY_HOUR) <= NOW()
AND tags LIKE '%cars%' )
UNION DISTINCT
(SELECT 't2', navid, '', clicks, tags
FROM t2
WHERE DATE_ADD(d, INTERVAL '0 8' DAY_HOUR) <= NOW()
AND tags LIKE '%cars%' )
UNION DISTINCT
(SELECT 't3', navid, title, clicks, tags
FROM t3
WHERE DATE_ADD(d, INTERVAL '0 8' DAY_HOUR) <= NOW()
AND tags LIKE '%cars%' )