如何从php中的两个表中选择数据

时间:2016-02-26 18:22:41

标签: php mysql mysqli

我有两个表新闻和主题

public class Contract
{
   ...
   public Product Product { get; set; }
   ...
}

public class Product
{
    ...
    public Contract Contract { get; set; }
    ...
}

table tb_Contract
(
   idContract,
   idProduct
)

table tb_Product
(
   idProduct,
   description,
)

我想选择两个表的标题

我试过这段代码,但它不起作用

      news                        topics

id  title  text                id  title  text
--- ----- ----                 --- -----  ----
1   abc    aa                   1   hgd    hh   
2   def    bb                   2   ddf    ff
3   gfs    cc                   3   gty    gg
4   sdfv   dd                   4   bbc    tt

3 个答案:

答案 0 :(得分:1)

由于我没有看到将两张桌子绑在一起的钥匙,因此您可以使用UNION参考谷歌获取更多信息,例如:

SELECT title FROM news
UNION
SELECT title FROM topics;

答案 1 :(得分:1)

假设您想要一个包含两个表中所有(唯一)标题的结果集,无论这些表是否以任何方式相关......

SELECT title FROM news

UNION 

SELECT title FROM topics

有关详细信息,选项和详细信息,请参阅MySQL's UNION文档。

要显示结果,它与您之前的代码大致相同:

$select_newtopics = $mysqli->query("SELECT title FROM news

UNION 

SELECT title FROM topics");

$num_newtopics = $select_newtopics->num_rows;

while ($row = $select_newtopics->fetch_array(MYSQL_ASSOC)) {
    echo $row['title'] . '<br>';
}

答案 2 :(得分:0)

您的表必须共享一个id,例如将news_id添加到主题表以链接两个表

    news                        topics

id title text id title title text news_id --- ----- ---- --- ----- ---- ------- 1 abc aa 1 hgd hh 1 2 def bb 2 ddf ff 2 3 gfs cc 3 gty gg 3 4 sdfv dd 4 bbc tt 4

请更新您的数据库结构,您可以使用JOIN

<?
 $select_newtopics = $mysqli->query("SELECT news.id AS newsId,
                                 news.title AS  newsTitle, 
                                 news.text AS newsText, 
                                 topics.id AS topicId, 
                                 topics.title AS topicTitle, 
                                 topics.text AS topictext
                                 FROM topics
                                 LEFT JOIN news ON topics.news_id = news.id
                                 ORDER BY topics.id
                                 DESC");
 $num_newtopics = $select_newtopics->num_rows;

 while ($rows_newtopics = $select_newtopics->fetch_array(MYSQL_ASSOC)){

        $id_newtopics       = $rows_newtopics ['topicId'];
        $title_newtopics    = $rows_newtopics ['topicTitle'];

        echo $title_newtopics."<br>";

} ?&GT;