mysql query dont gets all posts - php

I have a MYSQL query who have to list all post i want it to post. But it dont do it. It shows posts when i have more then one post in the table "meaOrder" with the same "ordCode". But when i have only on post in meaOrder, i don't show it. What can i do?
SELECT koden, wish, rnamn, bild, pris, cname, onsktext
FROM (
SELECT m.wishText as onsktext, m.meaOID as midn, m.ordcode as koden, w.wish as wish, r.meaName as rnamn, r.meaImg as bild,
r.meaPrice as pris, k.catName as cname from cats k, meals r, wishes w,
meaOrder m
join orders c on c.ordNR=4401
WHERE c.ordStatus=1 AND m.ordNR=c.ordNR AND m.meaID=r.meaID AND m.wishesID=w.id
AND r.catID=k.catID
) T
GROUP BY koden, rnamn, bild, pris, cname
ORDER BY midn DESC
TABLE orders
http://grab.by/m74E
TABLE meaOrder http://grab.by/m74Q

Try replacing the JOIN with RIGHT JOIN in this case. The difference is explained at JOIN Syntax page in MySQL docs . In short - JOIN returns row only if there are corresponding rows in both joined tables (inner join). LEFT JOIN / RIGHT JOIN return all rows from one of the tables and corresponding row if it exists from the other table (those are outer joins)

Do you need a subselect?
This seems to cover it:-
SELECT m.ordcode AS koden, w.wish AS wish, r.meaName AS rnamn, r.meaImg AS bild, r.meaPrice AS pris, k.catName AS cname, m.wishText AS onsktext
FROM cats k
INNER JOIN meals r ON r.catID = k.catID
INNER JOIN meaOrder m ON m.meaID = r.meaID
INNER JOIN wishes w ON m.wishesID = w.id
INNER JOIN orders c ON m.ordNR = c.ordNR
WHERE c.ordStatus = 1
AND c.ordNR = 4401
GROUP BY m.ordcode, r.meaName, r.meaImg, r.meaPrice, k.catName
ORDER BY midn DESC

Related

Left Join - Select ALL from left table but select only the latest from right table

I have 2 tables, borrowers and loans. I want to display on the main page the list of ALL borrowers with or without loans. If with loan, display the newest one.
I have the following sql query, basically it returns the above description except it displays the very first loan of the borrower instead of the latest one.
(Side note: I used GROUP BY to avoid duplicates. Without it the query returns duplicated borrower names if they have multiple loans. Just wanted to know if this is an efficient way of doing so.)
SELECT b.b_id,
b.isdeleted,
b.picture,
b.firstname,
b.middlename,
b.lastname,
b.address,
b.contactno,
b.birthday,
b.businessname,
b.occupation,
b.comaker,
b.comakerno,
b.remarks,
b.datecreated,
b.activeloan,
l.l_id,
l.amount,
l.payable,
l.balance,
l.mode,
l.term,
l.interestrate,
l.amortization,
l.releasedate,
l.duedate,
l.status,
l.c_id
FROM borrowers as b
LEFT JOIN loans as l ON b.b_id = l.b_id
WHERE b.isdeleted = 0
GROUP BY b.b_id
It seems the below query does exactly what i wanted.
I added the below subquery on the "ON" clause.
(SELECT MAX(l_id)
FROM jai_db.loans as l2
WHERE l2.b_id = b.b_id LIMIT 1)
SELECT b.b_id, b.isdeleted, b.picture, b.firstname, b.middlename, b.lastname, b.address, b.contactno,
b.birthday, b.businessname, b.occupation, b.comaker, b.comakerno, b.remarks, b.datecreated, b.activeloan,
l.l_id, l.amount, l.payable, l.balance, l.mode, l.term, l.interestrate, l.amortization,
l.releasedate, l.duedate, l.status, l.c_id
FROM jai_db.borrowers as b
LEFT JOIN jai_db.loans as l
ON l.l_id = (SELECT MAX(l_id)
FROM jai_db.loans as l2
WHERE l2.b_id = b.b_id LIMIT 1)
WHERE b.isdeleted = 0

mysql join return 0 for one column with other columns intact

I wish to join multiple tables like- Categories, menus, restaurants, reviews, etc.
to return the restaurants that provide the inserted food with their prices.
Everything works except numberOfReviews in reviews table.
If a restaurant has no reviews then output should be 0 for numOfReviews column but other column values should be retrieved i.e. price, name, etc.
With following query I get all fields as null and count(numReviews) as 0:
select r.id
,r.`Name`
,r.`Address`
,r.city
,r.`Rating`
,r.`Latitude`
,a.`AreaName`
,m.`Price`
,count(rv.id)
from `categories` c, `menus` m, `restaurants` r, areas a, reviews rv
where m.`ItemName`="tiramisu"
and c.`restaurant_id`=r.`id`
and m.`category_id`=c.id
and r.`AreaId`=a.`AreaId`
and if I can't match rv.restaurant_id=r.id in where clause(obviously).
Where am I getting wrong? How do I solve this?
edited
select r.id,
r.`Name`,
r.`Address`,
r.city,
r.`Rating`,
r.`Latitude`,
a.`AreaName`,
m.`Price`,
r.`Longitude`,
r.Veg_NonVeg,
count(rv.id)
from restaurants r LEFT JOIN `reviews` rv on rv.`restaurant_id`=r.`id`
inner join `categories` c on c.`restaurant_id` = r.id
inner join `menus` m on m.`category_id` = c.id
inner join `areas` a on a.`AreaId` = r.`AreaId`
where m.`ItemName`="tiramisu"
First of all, don't use this old school syntax for the jointures.
Here is a query that may solve your problem:
SELECT R.id
,R.Name
,R.Address
,R.city
,R.Rating
,R.Latitude
,R.Longitude
,A.AreaName
,M.Price
,R.Veg_NonVeg
,COUNT(RV.id) AS numOfReviews
FROM restaurants R
INNER JOIN categories C ON C.restaurant_id = R.id
INNER JOIN menus M ON M.category_id = C.id
INNER JOIN areas A ON A.AreaId = R.AreaId
LEFT JOIN reviews RV ON RV.restaurant_id = R.id
WHERE M.ItemName = 'tiramisu'
GROUP BY R.id, R.Name, R.Address, R.city, R.Rating, R.Latitude, R.Longitude, A.AreaName, M.Price, R.Veg_NonVeg
I used explicit INNER JOIN syntax instead of your old school syntax and I modified the jointure with table reviews in order to get the expected result. The GROUP BY clause is required to use the aggregate function COUNT, every rows will be grouped by the enumerated columns (every column except the one used by the function).
Here is another solution that simplify the GROUP BY clause and allow the modification of SELECT statement without having to worry about the fact that every columns need to be part of the GROUP BY clause:
SELECT R.id
,R.Name
,R.Address
,R.city
,R.Rating
,R.Latitude
,R.Longitude
,A.AreaName
,M.Price
,R.Veg_NonVeg
,NR.numOfReviews
FROM restaurants R
INNER JOIN (SELECT R2.id
,COUNT(RV.id) AS numOfReviews
FROM restaurants R2
LEFT OUTER JOIN reviews RV ON RV.restaurant_id = R2.id
GROUP BY R2.id) NR ON NR.id = R.id
INNER JOIN categories C ON C.restaurant_id = R.id
INNER JOIN menus M ON M.category_id = C.id
INNER JOIN areas A ON A.AreaId = R.AreaId
WHERE M.ItemName = 'tiramisu'
As you can see here I added a new jointure on a simple subquery that does the aggregation job in order to provide me the expected number of reviews for each restaurant.
Hope this will help you.

Search keyword and apply filters

I am encountering a problem I cannot bypass by myself and I that's why I am posting this question. There are a lot of other posts out there that give me half of the answer and I don't really know how to get it done.
I have 3 tables that contain informations about an ad. One table is "ad_names", another is "ad_locations" and the last one is "ad_details".
Ad_Names has : ad_title, ad_description, ad_date_added
Ad_Locations has : ad_country, ad_region, ad_city
Ad_Details has : ad_price, ad_author, ad_active
Basically I want apply location and details filters for an ad with a certain title.
For example, I want to search "food" keyword in ad-titles and then apply filters like "only from Kansas" or "Only from Kansas + price higher than 500USD". How do I do it?
first you will need to join the tables. do you know if you have a foreign key on the tables? like is there an Ad_ID field on all 3 tables? if the tables are large you may also want to index the fields you are searching. once you have all the data you will "filter" it with a where clause.
http://www.w3schools.com/sql/sql_where.asp
select * from ad_names as A
join ad_location as L on A.key=L.key
join ad_details as D on A.key=D.key
where A.ad_title like '%food%' and L.ad_region = 'Kansas' and D.ad_prics > 500;
depending on how your database is setup, you may get a cartesian result there, so you would have to look at your join. maybe a left outer join limiting the join in an on statement instead of in the where. it is hard to say without more information.
Join types
Assuming that Ad is a table with primary key id, which is a foreign key in each of the other tables (ad_id) then something along the lines of:
Location:
SELECT *
FROM Ad A
INNER JOIN Ad_Names N ON N.ad_id = A.id
INNER JOIN Ad_Locations L ON L.ad_id = A.id
INNER JOIN Ad_Details D ON D.ad_id = A.id
WHERE N.ad_title LIKE '%food%' AND L.ad_city = 'Kansas'
Price and location:
SELECT *
FROM Ad A
INNER JOIN Ad_Names N ON N.ad_id = A.id
INNER JOIN Ad_Locations L ON L.ad_id = A.id
INNER JOIN Ad_Details D ON D.ad_id = A.id
WHERE N.ad_title LIKE '%food%' AND L.ad_city = 'Kansas' AND D.ad_price > 500

MySQL RIGHT JOIN SUM() from Table B to Info on Table A

Basically I have a load of product information on Table A. This include the product_id which is the common id over both tables. On Table B I have a list of votes which include product_id, username, thevote(could be +1 or -1).
So basically I want to have a table of 'Table A' with a additional column containing the SUM of all the votes for that product_ID. I am sure there is an easy way to do this. Which i think is using 'right join'.
I still want it to list all the products in Table A regardless if they have a single +1 or -1 vote.
Many thanks in advance peoples!
You could use group by statement and left join like:
select productName, sum(vote) as productVoteSum
from `products` p
left join `products_votes` pv on p.id = pv.productId
where productName like '%chocolat%'
group by p.id
order by productName;
You can do a LEFT JOIN (that goes through all the information on tableA and puts the SUM in the ones that have the matching product_id on tableB), then you add the SUM(b.thevote) and group by the remaining columns
SELECT a.product_id,a.productName,SUM(b.thevote)
FROM tableA a
LEFT JOIN tableB b ON a.product_id = b.product_id
GROUP BY a.product_id, a.productName
SELECT a.*, SUM(b.votes) FROM TableA a LEFT JOIN TableB b ON a.prouct_id=b.product_id
GROUP BY a.product_id

Performing a join on ZenCart's address book entries

I have the following bits of code:
$referrers_query =
select c.customers_id, c.customers_firstname, c.customers_lastname,
c.customers_email_address, c.customers_telephone, a.entry_street_address,
a.entry_city, a.entry_state, a.entry_country_id, n.countries_name,
a.entry_zone_id, a.entry_postcode, r.referrer_customers_id,
r.referrer_key, r.referrer_homepage, r.referrer_approved,
r.referrer_banned, r.referrer_commission from customers as c,
address_book as a, referrers as r, countries as n
where a.entry_country_id = n.countries_id and c.customers_id = r.referrer_customers_id
and a.address_book_id = c.customers_default_address_id order by c.customers_lastname;
What I would like to do, is instead of making a WHERE clause join, I'd like to nest the joins.
There are five database tables noted above.
customers, address_book, referrers, countries, zones.
But I have no idea where to get started. The main problem with this is using the above statement, I seem to lose a few records from the select. This is because some records are using a 'zone_id' = 0. A fix to this was to simply create a blank record for 0 but besides that, can I use a join to fix this?
The query written with explicit JOINs:
SELECT c.customers_id, c.customers_firstname, c.customers_lastname,
c.customers_email_address, c.customers_telephone, a.entry_street_address,
a.entry_city, a.entry_state, a.entry_country_id, n.countries_name,
a.entry_zone_id, a.entry_postcode, r.referrer_customers_id,
r.referrer_key, r.referrer_homepage, r.referrer_approved,
r.referrer_banned, r.referrer_commission
FROM customers AS c
JOIN referrers AS r ON (c.customers_id = r.referrer_customers_id)
JOIN address_book AS a ON (a.address_book_id = c.customers_default_address_id)
JOIN countries AS n ON (a.entry_country_id = n.countries_id)
ORDER BY c.customers_lastname
If you want to also get the info from the zones table if a match exists, you would need to add a LEFT JOIN like this:
SELECT c.customers_id, c.customers_firstname, c.customers_lastname,
c.customers_email_address, c.customers_telephone, a.entry_street_address,
a.entry_city, a.entry_state, a.entry_country_id, n.countries_name,
a.entry_zone_id, a.entry_postcode, r.referrer_customers_id,
r.referrer_key, r.referrer_homepage, r.referrer_approved,
r.referrer_banned, r.referrer_commission
FROM customers AS c
JOIN referrers AS r ON (c.customers_id = r.referrer_customers_id)
JOIN address_book AS a ON (a.address_book_id = c.customers_default_address_id)
JOIN countries AS n ON (a.entry_country_id = n.countries_id)
LEFT JOIN {zones table name} AS z ON (z.{zones id column name} = a.entry_zone_id)
ORDER BY c.customers_lastname
and also add the columns you want to select to the top of the query. A LEFT JOIN always returns a result from the left table (first one listed) and if there is no match in the right table, it returns NULLs for the right table's columns.

Categories