如何在结果中加入2个结果显示

时间:2016-10-29 06:57:29

标签: php mysql join

您好我有两个问题:
这是用于选择列表:

select *  from buy

购买表格:

ID | product_id| Time

我希望为每条记录添加文本,这是查询每条记录的选择文本

Updated

最终结果是这样的

    {
        "ID": "13",
        "product_id": "4",
        "Date": "2016-10-28 00:00:00",
        {
            "txt_1": "hi this is txt 1",
            "txt_2": "this is txt 2"
        }
    }

我从这段代码中使用了该结果:

    $result = $con->executeNoneQuery($sql_1);//get all records
    while($row=mysql_fetch_object($result)){
        $result2 = $con->executeNoneQuery($sql_2);//get txt for every records
    }

现在我想知道我可以通过一个SQL查询获得两个结果吗?或者更好的主意?
像这样的东西

    {
        "ID": "13",
        "product_id": "4",
        "Date": "2016-10-28 00:00:00",
        "txt_1": "hi this is txt 1",
        "txt_2": "this is txt 2"
    }

更新 对不起,我对真正的第二次查询感到困惑 secend查询是这样的:

select txt from product_id,text_list where text_list.id=product_id.id and product_id='a1' order by rand() limit 2

3 个答案:

答案 0 :(得分:0)

Flow流程代码:

Select b.ID,b.product_id,b.Time,t.text from buy b RIGHT JOIN text t ON p.product_id = t.product_id; 

答案 1 :(得分:0)

您可以使用此查询:

SELECT t2.*,GROUP_CONCAT(t.text SEPARATOR '###') as txt 
FROM buy t2 
LEFT JOIN txt t on t2.id = t.product_id
LEFT JOIN product_id p on t.id=p.id
where t.product_id='al' 
GROUP by t.product_id

然后在PHP代码中尝试:

$txts = explode("###", txt);

获取每一行的文本字段数组

答案 2 :(得分:0)

您的预期查询是:

Select a.id,a.product_id,a.Time,b.txt_1, b.txt_2 from 
buy a LEFT JOIN text b ON a.id = b.product_id order by rand() limit 2;

更多详情http://www.w3schools.com/sql/sql_join.asp