如何在Mysql Union中识别表

时间:2018-04-14 07:21:11

标签: php mysql sql mysqli

我有查询如下

SELECT * FROM ( 
    (
        SELECT * FROM comments 
        WHERE user_id = '66' AND product_id = '3' 
        AND status = 1 
    ) 
    UNION ALL 
    (
        SELECT * FROM comments_reply 
        WHERE user_id = '66' AND product_id = '3'
        AND status = 1 ) 
    ) results 
ORDER BY datetime DESC

从两个tabel获取数据并显示为datetime.now frontside我显示此数据。但现在我想知道哪个数据来自哪个表。

因为我正在调用一个模态来通过此

在模态中显示注释
<span class="showcomment text-danger"
     data-cid = <?=$row[0]?>>view Comment</span>

但是$row[0]给了我一个身份但我怎么能确定这个id来自哪个表?

3 个答案:

答案 0 :(得分:3)

我会像您想要的tablename一样重写您的查询

SELECT 'comments' as table_name, col1, col2,... coln FROM comments c
WHERE user_id = '66' AND product_id = '3' 
AND status = 1  UNION ALL 
SELECT 'comments_reply' as table_name, col1, col2,... coln FROM comments_reply cr
WHERE user_id = '66' AND product_id = '3'
ORDER BY col DESC

并且,我怀疑如果你有user_idproduct_id有数字类型,那么你应该只使用没有单引号的值。

where user_id = 66 AND product_id = 3

答案 1 :(得分:0)

您可以为两个表中的每个表添加一个列,并使用自定义字符串填充它。例如,第一个子查询将像以下一样开始,新列“table_name”... select *,'comments'table_name from comments ...

答案 2 :(得分:0)

SELECT * FROM ( 
    (
        SELECT "comments" as tablename,* FROM comments 
        WHERE user_id = '66' AND product_id = '3' 
        AND status = 1 
    ) 
    UNION ALL 
    (
        SELECT "comments_reply" as tablename,* FROM comments_reply 
        WHERE user_id = '66' AND product_id = '3'
        AND status = 1 ) 
    ) results 
ORDER BY datetime DESC