I have an SQL query to load items from my database.
$sql_query = "SELECT * FROM pagina_info
WHERE kwali='Luxuary' AND
id IN (
SELECT CASE WHEN kwali='Luxuary' THEN min(id)
ELSE max(id)
END
FROM pagina_info
GROUP BY product_name
)
AND voorraad>='1'
LIMIT ".$getal1.", ".$getal2."";
Now my question, is there a word that i can use in my ELSE state for taking the next value?
in my select i have THEN min(id) ELSE max(id), instead of max(id) i need a word or something for next value.
I can't find anything usefull hopefully anyone here can help me.
Bram
There is no key word to get the next id. But I am unsure if you mean the next id for that series of records, or the next id that will be assigned as an auto increment primary key.
Assuming the first you could use a user variable to add a sequence number, or you could join the table against itself where the 2nd copy has a larger id but matches on the product name.
Depending on your exact requirements (some table layouts and test data would help) then something like one of these would work.
Firstly, sub query being used with an IN clause
SELECT *
FROM pagina_info
WHERE kwali='Luxuary'
AND id IN
(
SELECT CASE
WHEN kwali='Luxuary' THEN min(a.id)
ELSE min(b.id)
END
FROM pagina_info a
LEFT OUTER JOIN pagina_info b
ON a.product_name = b.product_name
AND a.id < b.id
GROUP BY a.product_name
)
AND voorraad>='1'
LIMIT ".$getal1.", ".$getal2."";
Or doing a join against a sub query.
SELECT pagina_info.*
FROM pagina_info
INNER JOIN
(
SELECT CASE
WHEN kwali='Luxuary' THEN min(a.id)
ELSE min(b.id)
END AS id
FROM pagina_info a
LEFT OUTER JOIN pagina_info b
ON a.product_name = b.product_name
AND a.id < b.id
GROUP BY a.product_name
) c
ON pagina_info.id = c.id
WHERE pagina_info.kwali='Luxuary'
AND pagina_info.voorraad>='1'
LIMIT ".$getal1.", ".$getal2."";
Related
I have an articles table that and I am displaying it in the homepage in a while loop. Inside the while loop I want to display the comments count and images count for each article.
It is working for me now, but it is three queries in total, I am trying to combine it in the first query and then just display all of them in one while loop. Here is what I am trying to achieve:Articles page
The current format I am following:
//a represents articles table, c represents comments table, i represents image table
$query = mysqli_query($conn, "SELECT a.a_id, a.title, a.datetime, a.user_id FROM a ORDER BY a.datetime DESC");
while($fetch = mysqli_fetch_assoc($query){
$imageQ = msqli_query($conn, "SELECT COUNT(image_path), image_path FROM i WHERE a_id = '$fetch['a_id']'");
$imageFetch = mysqli_fetch_assoc($imageQ);
$commentQ = mysqli_query($conn, "SELECT COUNT(comment_id) FROM c WHERE a_id = '$fetch['a_id']'");
$commentFetch = mysqli_fetch_assoc($commentQ);
}
I want to cram all of these queries into one single query that fetches the article and comments count and image count for each article and the first image.
The images and comments are separate dimensions of the data. So, you have to be careful about how to bring them together. In your case, you can aggregate the values before doing the joins:
SELECT a.a_id, a.title, a.datetime, a.user_id,
i.num_images, c.num_comments
FROM a LEFT JOIN
(SELECT a_id, COUNT(image_path) as num_images
FROM i
GROUP BY a_id
) i
ON i.a_id = a.a_id LEFT JOIN
(SELECT a_id, COUNT(comment_id) as num_comments
FROM c
GROUP BY a_id
) c
ON c.a_id = a.a_id
ORDER BY a.datetime DESC;
You can use mysql nested queries something like
SELECT a.,tab1.,tab2.* FROM a INNER JOIN (SELECT * FROM b ) as tab1 INNER JOIN (SELECT * FROM c) as tab2
Hope this can get you to get desired output.
Thanks
I have a table structure like following:
Users => Histories <= Brands
Histories table keeps following columns: userId, brandId, points
I have a query like following:
select b.id, sum(h.points),h.brandId
from brands b left join
histories h
on b.id = h.brandid and h.userId = 2866
group by b.id;
This query returns me brands where USER made points and didnt make any points at all..
I wanna add a filter to a brandId as well so that the query doesn't returns all results, but a single result at a time depending what brandId has been sent to the query... How can I and where can I add a statement which would return me a single record for this query?? So basically I just need to pass brandId = to something statement, leaving the query it self as it is right now ... :)
For example if brand id is 100:
select b.id, sum(h.points),h.brandId
from brands b left join
histories h
on b.id = h.brandid and h.userId = 2866
where b.id=100
group by b.id
limit 1;
I have two tables,
TABLE 1 has many of each client and campaign and is very large
TABLE 2 has only one of each client and campaign and is small.
So I want to get the lastest(highest ID) from TABLE 1 where it matches the client and campaign in TABLE 2 and only one of each.
I have tried MAX, and playing with the order by etc, but cant get it working....
The results I get are choosing the lowest ID from TABLE 1 (I want highest)
$result2 = mysql_query("SELECT table1.client,table1.campaign,table1.id
FROM table1
LEFT OUTER JOIN
table2
ON (table2.client = table1.client)
AND (table2.campaign = table1.campaign )
WHERE (table2.enabled != 'disabled')
group by campaign asc
order by client,campaign,id asc
");
Help needed....
SELECT * FROM table1
INNER JOIN
(
SELECT MAX(table1.id) AS id FROM table1
INNER JOIN table2 ON table2.client = table1.client AND table2.campaign=table1.campaign and table2.enabled != 'disabled'
GROUP BY table1.client, table1.campaign
) AS m ON m.id = table1.id
I think that's what you're asking for. For each combination of client and campaign that exists in each table, it will give you the highest ID in table 1.
I currently have this left join as part of a query:
LEFT JOIN movies t3 ON t1.movie_id = t3.movie_id AND t3.popularity = 0
The trouble is that if there are several movies with the same name and same popularity (don't ask, it just is that way :-) ) then duplicate results are returned.
All that to say, I would like to limit the result of the left join to one.
I tried this:
LEFT JOIN
(SELECT t3.movie_name FROM movies t3 WHERE t3.popularity = 0 LIMIT 1)
ON t1.movie_id = t3.movie_id AND t3.popularity = 0
The second query dies with the error:
Every derived table must have its own alias
I know what I'm asking is slightly vague since I'm not providing the full query, but is what I'm asking generally possible?
The error is clear -- you just need to create an alias for the subquery following its closing ) and use it in your ON clause since every table, derived or real, must have its own identifier. Then, you'll need to include movie_id in the subquery's select list to be able to join on it. Since the subquery already includes WHERE popularity = 0, you don't need to include it in the join's ON clause.
LEFT JOIN (
SELECT
movie_id,
movie_name
FROM movies
WHERE popularity = 0
ORDER BY movie_name
LIMIT 1
) the_alias ON t1.movie_id = the_alias.movie_id
If you are using one of these columns in the outer SELECT, reference it via the_alias.movie_name for example.
Update after understanding the requirement better:
To get one per group to join against, you can use an aggregate MAX() or MIN() on the movie_id and group it in the subquery. No subquery LIMIT is then necessary -- you'll receive the first movie_id per name withMIN() or the last with MAX().
LEFT JOIN (
SELECT
movie_name,
MIN(movie_id) AS movie_id
FROM movies
WHERE popularity = 0
GROUP BY movie_name
) the_alias ON t1.movie_id = the_alias.movie_id
LEFT JOIN movies as m ON m.id = (
SELECT id FROM movies mm WHERE mm.movie_id = t1.movie_id
ORDER BY mm.id DESC
LIMIT 1
)
you could try to add GROUP BY t3.movie_id to the first query
Try this:
LEFT JOIN
(
SELECT t3.movie_name, t3.popularity
FROM movies t3 WHERE t3.popularity = 0 LIMIT 1
) XX
ON t1.movie_id = XX.movie_id AND XX.popularity = 0
On MySQL 5.7+ use ANY_VALUE & GROUP_BY:
SELECT t1.id,t1.movie_name, ANY_VALUE(t3.popularity) popularity
FROM t1
LEFT JOIN t3 ON (t3.movie_id=t1.movie_id AND t3.popularity=0)
GROUP BY t1.id
more info
LEFT JOIN only first row
https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html
Easy solution to left join the 1 most/least recent row is using select over ON phrase
SELECT A.ID, A.Name, B.Content
FROM A
LEFT JOIN B
ON A.id = (SELECT MAX(id) FROM B WHERE id = A.id)
Where A.id is the auto-incremental primary key.
LEFT JOIN (
SELECT id,movie_name FROM movies GROUP BY id
) as m ON (
m.id = x.id
)
// Mysql
SELECT SUM(db.item_sales_nsv) as total FROM app_product_hqsales_otc as db
LEFT JOIN app_item_target_otc as it ON
db.id = (SELECT MAX(id) FROM app_item_target_otc as ot WHERE id = db.id)
and db.head_quarter = it.hqcode
AND db.aaina_item_code = it.aaina_item_code AND db.month = it.month
AND db.year = it.year
WHERE db.head_quarter = 'WIN001' AND db.month = '5' AND db.year = '2022' AND db.status = '1'
I feel like I'm writing a word problem, but it's really puzzling me and I really hope someone here can solve it:
I want to select one row from table A. Table A includes the attributes Name and Number. But before I finish the query, I want to check it against table B. Table B includes Name, Number, and the Username of the user.
Based on the users' input, it inserts rows into table B that include their Username along with a Name and Number.
Now in my query where I select a row from table A, I want to make sure that there are no rows in table B with matching Name and Number for that particular User.
I have tried WHERE (A.Name = B.Name AND A.Number = B.Number AND B.Username != '$username') but I think I was way off base with that.
Any help would be... amazing.
SELECT
A.id
FROM
A
LEFT OUTER JOIN B ON
(A.Name = B.Name AND A.Number = B.Number)
WHERE
B.Name IS NULL
AND B.Number IS NULL
AND B.Username = ?
select a.id
from a
where
a.name=:name
and
not exists(select 1 from b where b.id=a.id and b.name=a.name)
IF NOT EXISTS ( SELECT 1
FROM tableA a
INNER JOIN tableB b
ON a.name = b.name
AND a.number= b.number
AND b.UserName = 'user' and b.name = 'name'and b.number = 'number')
SELECT *
FROM tableA x
WHERE x.name = 'name'and x.number = 'number'