如何在一个查询中组合2个选择?

时间:2015-11-03 21:49:54

标签: php mysql sql

我有sql查询从第一个表中选择一些东西使用第二个参数,然后我需要从第二个表中获取一些列除了第一个 代码看起来像那样

SELECT 
  entry AS entry,
  ItemLevel AS ItemLevel,
  RequiredLevel AS RequiredLevel,
  InventoryType AS InventoryType,
  Quality AS Quality,
  class AS class,
  subclass AS subclass 
FROM item_template 
WHERE entry IN (SELECT entry FROM locales_item WHERE name_loc8 LIKE ? ) 
ORDER BY ItemLevel DESC; 

SELECT entry, name_loc8, description_loc8 FROM locales_item WHERE name_loc8 LIKE ?

但它引发了错误

  

您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以便使用接近' SELECT条目,name_loc8,description_loc8 FROM locales_item WHERE name_loc8 LIKE'在第1行

如何解决这个问题?

5 个答案:

答案 0 :(得分:2)

您应该使用join连接两个表:

SELECT 
  item_template.entry AS entry,
  ItemLevel AS ItemLevel,
  RequiredLevel AS RequiredLevel,
  InventoryType AS InventoryType,
  Quality AS Quality,
  class AS class,
  subclass AS subclass 
FROM item_template inner join locales_item 
on item_template.entry = locales_item.entry 
 WHERE name_loc8 LIKE ?  
ORDER BY ItemLevel DESC; 

答案 1 :(得分:1)

如果条目是唯一键,那么您可以将两个表一起加入

SELECT it.stuff, li.stuff 
FROM item_template it 
JOIN locales_item li ON li.entry = it.entry
WHERE li.name_loc8 LIKE "some string"
ORDER BY it.ItemLevel DESC

这消除了对IN()的从属子查询的需要,因为加入表已经过滤了像

那样的过滤器

答案 2 :(得分:0)

如果你想加入两个查询的结果,你可以使用UNION,但我认为你在这里的目的是将两个表中的匹配记录加入一个查询,你可以用{{3 }}

通过您的示例,我认为您正在寻找的是这样的查询:

if (rand <= 20 ){//Miss
    JOptionPane.showMessageDialog(null, "You have missed your opponent like a fool.\nYour Opponent has "+life2+" remaining.");
}
else if (rand <= 34){//Wiff
    int Wiff = chance.nextInt(10)+1;
    life = life-Wiff;
    JOptionPane.showMessageDialog(null, "You have stubbed your toe. Idiot.\nYou have "+life+" remaining."+Wiff);
}
else if (rand <= 74){//Regular Hit
    int regHit = chance.nextInt(20)+1;
    life2 = life2-regHit;
    JOptionPane.showMessageDialog(null, "You have hit your opponent!"+regHit);
}
else if (rand <= 90){//CritHit
    int critHit = chance.nextInt(40)+1;
    life2 = life2-critHit;
    JOptionPane.showMessageDialog(null, "You have dealt critical damage!"+critHit);
}
else {//Fatality.      
    JOptionPane.showMessageDialog(null, "Fatality!\nYou stabbed your opponent in the foot,\ndrug your knife throught"
            + "his belly,\nand impaled his head on your knife!");
    System.exit(0);
}

答案 3 :(得分:0)

试试这个

SELECT 
  t1.entry AS entry,
  t2.name_loc8,
  t2.description_loc8
  t1.ItemLevel AS ItemLevel,
  t1.RequiredLevel AS RequiredLevel,
  t1.InventoryType AS InventoryType,
  t1.Quality AS Quality,
  t1.class AS class,
  subclass AS subclass 
FROM item_template t1
left join locales_item t2 on t1.entry = t2.entry 
WHERE t2.name_loc8 LIKE '%addyourtexthere%'----just change the text between the percent signs to the string your looking for  
ORDER BY ItemLevel DESC; 

如果您使用相同的名称,则每列之后也不需要“AS”。

答案 4 :(得分:-1)

//使用连接查询

选择a.field1,a.field2,b.field3,b.field4 FROM table1 a,table2 b WHERE a.field1 = b.field3 ORDER BY a.field4