编写SQL查询

时间:2011-07-25 04:21:14

标签: mysql join

我有两张桌子:

product_description(name, product_id

产品(数量,stock_status_id,价格, product_id

我要做的是运行一个查询来获取上述数据,但我不确定如何实现连接以从两个表中获取连接数据。

解决

我做了以下事情:

SELECT product_description.name, product.quantity,product.price
FROM product
INNER JOIN product_description
ON product.product_id=product_description.product_id
ORDER BY product_description.name 

3 个答案:

答案 0 :(得分:1)

假设您在每个表中都匹配product_id,这是一个查询,它将使用隐式连接返回您需要的数据:

SELECT product.product_id, name, quantity, stock_status_id, price
FROM product, product_description
WHERE product.product_id = product_description.product_id

更新:

这正如我所料。以下是两个可能对您有帮助的表转储以及查询的输出。

产品表:

--
-- Table structure for table `product`
--

CREATE TABLE IF NOT EXISTS `product` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(256) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`product_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`product_id`, `name`) VALUES
(1, 'Croissant'),
(2, 'Danish');

product_description表:

--
-- Table structure for table `product_description`
--

CREATE TABLE IF NOT EXISTS `product_description` (
  `product_id` int(11) NOT NULL,
  `quantity` int(11) NOT NULL,
  `stock_status_id` int(11) NOT NULL,
  `price` double NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `product_description`
--

INSERT INTO `product_description` (`product_id`, `quantity`, `stock_status_id`, `price`) VALUES
(1, 6, 2, 12.5),
(2, 13, 1, 19.25);

以上查询的输出:

"1","Croissant","6","2","12.5"
"2","Danish","13","1","19.25"

答案 1 :(得分:0)

也许是这样的?

select p.id, p.quantity, p.stock_status_id, p.price, d.name
from Product p inner join `Product Description` d on d.product_id=p.id

虽然我仍然不确定表格架构在问题中的描述实际上是什么样的。

答案 2 :(得分:0)

SELECT
   -- name each column you want here
   -- prefix columns from the PRODUCT table with its alias like so:
   p.product_id,

   -- prefix columns from the other table as its alias
   d.quantity
FROM
    PRODUCT p  -- name of your PRODUCT table aliased as p
INNER JOIN     -- join against your other table
    PRODUCT_DESCRIPTION d -- name of your other table aliased as d
ON
    p.product_id = d.product_id -- match the foreign keys

有关详细信息,请参阅INNER JOIN文档。

注意:这不会按原样运行,您需要在SELECT子句中提供每个表所需的列,并可能修复表名以匹配您的应用程序。 / p>