2014-10-02 137 views
-2

我的数据库中有下一个表。我需要确定用户购买的所有图书以及购买特定图书的所有用户。SQL查询无法正确运行

http://i.imgur.com/IPb0bmi.png

这些都是我的SQL请求,但不顺心的事:

select * 
from Livres 
where idCatalogue_fk in (
    select idCatalogue_fk 
    from ProduitsEtCommandes 
    where idCommande_fk in (
     select idCommande_fk 
     from CommandesEtUtilisateurs 
     where idUtilisateur_fk=1 
    ) 
); 


select * 
from Utilisateurs 
where idUtilisateur in (
    select idUtilisateur_fk 
    from CommandesEtUtilisateurs 
    where idCommande_fk in (
     select idCommande_fk 
     from Catalogue 
     where idCatalogue in (
      Select idLivre 
      from Livres 
      where idCatalogue=1 
      and title='Poezii' 
     ) 
    ) 
); 
+0

这些是嵌套'SELECT'语句。你最好用'JOIN's – ne1410s 2014-10-02 17:24:44

+1

什么地方出错?你能提供样本数据和期望的输出吗?编辑您的问题以包括其中的一些细节。 – 2014-10-02 17:30:42

+0

你是什么意思“出现问题”? – Kritner 2014-10-02 17:31:06

回答

2

我不知道法国... 有可能是拼写错误与表和列名。 ..使用where为特定用户或书籍添加过滤器。

编辑

你能不能做到这一点? (如果这是家庭作业,这不是一个数据库模型的一个很好的例子......顺便说一句)

select * from livres where idCatalogue_fk in ( 
    select idCatalogue_fk from produitsEtCommandes where idUtilisasteur_fk=1 
); 


-- note the misspelling comment i made up top... the ID in productsNCommands 
select * from utilisateurs where idUtilisateurs in ( 
     select idUtilisasteur_fk from produitsEtCommandes where idCatalogue_fk in (
           select idCatalogue_fk from livres where idLivre=1 
          ) 
    ); 

基本上......根据数据模型,您需要:

  • 加入里弗
  • 加入目录
  • 加入produitsEtCommandes
  • 加入commandes

这将给你每个livre-commande协会。然后根据您的需求进行过滤。

找到与用户Kim相关联的所有书籍(假设这个名字只有一个用户):

select * 
from  livres 
     join catalogue on livres.idCatalogue_fk=catalogue.idCatalogue 
     join produitsEtCommandes on produitsEtCommandes.idCatalogue_fk=catalogue.idCatalogue 
     join commandes on commandes.idCommande=produitsEtCommandes.idCommande_fk 
where commandes.nomClient = 'Kim' 

左右....你能做到这一点,那么......?

select * from livres where idLivre in ( 
      select distinct idLivre 
      from  livres 
         join catalogue on livres.idCatalogue_fk=catalogue.idCatalogue 
         join produitsEtCommandes on produitsEtCommandes.idCatalogue_fk=catalogue.idCatalogue 
      where idCommandes_fk=1) 

或....(那么难看)

select * 
from  livres, catalogue, produitsEtCommandes, commandes 
where livres.idCatalogue_fk=catalogue.idCatalogue and 
     produitsEtCommandes.idCatalogue_fk=catalogue.idCatalogue and 
     commandes.idCommande=produitsEtCommandes.idCommande_fk and 
     livres.title = 'Brave New World' 

哦,不一没有....

select * from livres where idCatalogue_fk in (
     select distinct idCatalogue from catalogue where idCatalogue in (
         (select distinct idCatalogue_fk from produitsEtCommandes where idCommandes_fk=1) 
       ) 
    ) 
+0

问题是我不允许使用内部连接,只需选择 – Nicolae 2014-10-02 17:36:18

+0

好吧....为什么这是完全一样的? – 2014-10-02 17:36:39

+0

@ gloomy.penguin也许是作业:P – Kritner 2014-10-02 17:39:26