2012-09-08 44 views
0

您好,我需要通过用户ID的单个mysql查询来显示多个表中的值。我遇到6名表如下...使用php获取和显示多个mysql表中的值使用php

国家:countryid,国家

状态:STATEID,Statename的,countryid

城市:cityid,城市,STATEID。

类别:categoryid,category_name。

sub_categories:sub_category_id,sub_category_name。

users:用户名,用户名,countryid,stateid,city,category_id和sub_category_id。

现在我想通过用户ID显示所有细节。我写了查询后,它显示国家,国家,类别和sub_category只有身份证,并不显示他们的名字。我使用select语句以及加入语句。但没有得到确切的输出。我有加入表格查询的基本知识。请提供想法或查询以显示我的输出。

回答

1

您可以使用加入这样的:

select 
    a.username, 
    b.country, 
    c.statename, 
    d.city, 
    e.category_name, 
    f.sub_category_name 
from 
    users a 
     join country b 
      on a.countryid=b.countryid 
     join state c 
      on a.stateid=c.stateid 
      and a.countryid=c.countryid 
     join city d 
      on a.city=d.cityid 
      and a.stateid=d.stateid 
     join categories e 
      on a.category_id=e.categoryid 
     join sub_categories f 
      on a.sub_category_id=f.sub_category_id 

我使用users.city列名从这里你的问题,是不是真的cityid虽然 - 这将更加符合您的列命名约定的其他。

0

数据库结构可能会更好,并且在您的表格中始终有统一的命名规则,因此更容易编写查询。

像这样的东西应该足够了:

SELECT c.country, s.statename, ci.city, ca.category_name, sc.sub_category_name FROM country c, state s, city ci, categories ca, sub_categories sc, users u WHERE u.country.id = c.countryid, u.stateid = s.stateid, u.city = ci.city, u.category_id = ca.categoryid AND u.sub_category_id = sc.sub_category_id ORDER BY u.userid DESC; 
相关问题