简体   繁体   中英

Select where two rows have the same column value and echo them

In the table "ogitems", I have a column called "itemname", "month", and "price".

There duplicate items, arranged by month.

I want to check "itemname" to see if any rows have the same value for itemname, and if yes, echo the "itemname" along with the last two months and the pricing for these two months.

EXAMPLE:

"itemname" = CHEESE CHEDDAR

CHEESE CHEDDAR is found in months 11 AND 12 (so there is two records/rows for CHEESE CHEDDAR). 11 has "price" of 51 while 12 has "price" of 54

I want to echo that information into an anchor tag...

<a href="pricetrend.php?date=<?php echo "" . $row['month'] . "" ?>&price1=<?php echo $price1; ?>&price2=<?php echo $price2; ?>&item=<?php echo "" . $row['itemname'] . ""?>;">

Basically , I am trying to grab the two most recent prices for one item and echo them into this anchor tag. Thanks in advance for any help!

select * from ogitems where itemname='CHEESE CHEDDAR' order by month desc limit 2

This sql statement should fix your problem

<?php 
  $result = mysql_query("select * from ogitems where itemname='CHEESE CHEDDAR' order by month desc limit 2")
  while ($row = mysql_fetch_assoc($result)) {
    echo $row["itemname"];
    echo $row["month"];
    echo $row["price"];
   }
?>

I am assuming that your month is a date field , this should work

SQL Fiddle link: http://sqlfiddle.com/#!2/d63a0/4

SELECT * FROM (
                 SELECT
                        o.itemname,
                        o.month,
                        ( SELECT price FROM ogitems i WHERE i.itemname = o.itemname AND i.month<o.month ORDER BY MONTH DESC LIMIT 1) AS last_month_price,
                        o.price AS current_month_price
                FROM
                    ogitems o
                ORDER BY
                    o.month DESC

              ) AS items
GROUP BY
  items.itemname
HAVING
  items.last_month_price IS NOT NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM