MySQL duplicate column on select from select - mysql

I have a few tables:
resources (which contains all the posts)
pid | usrnm | title | link | content | stitle | sdesc | at | likes
tags (which contains all the tags and an ID)
id | slug
retags (which connects the resource and it's tags)
pid | tid
I'm trying to make a search engine with which you can search by multiple tags, a search value and order the results by newest or most liked.
The SQL I use for searching by tags is:
SELECT
resources.pid, resources.title
FROM resources
INNER JOIN retags ON resources.pid = retags.pid
INNER JOIN tags ON retags.tid = tags.id
GROUP BY resources.pid
HAVING
SUM(tags.slug = 'tag-z')
AND
SUM(tags.slug = 'tag-y')
How can I apply the SQL for the search value WHERE title LIKE '%bla%' and order ORDER BY at DESC to this tag search SQL?
I tried select from select but kept gettings errors like "Duplicate column pid", "Column 'pid' in field list is ambiguous" etc
Can someone help me with this SQL? Thanks
I've tried everything in StackOverflow like using an alias for column name on oneSELECT pid as pid_ ... and even on both selects but I still kept getting the same duplicate column error.
EDIT: The SQL I've been getting errors from:
SELECT * FROM
(SELECT * FROM resources
INNER JOIN retags ON resources.pid = retags.pid
INNER JOIN tags ON retags.tid = tags.id
GROUP BY resources.pid
HAVING
SUM(tags.slug = 'A2') AND
SUM(tags.slug = 'AS')
) AS tsr WHERE tsr.title LIKE '%bla%' ORDER BY tsr.`at` DESC
This is just one of them, I've tried a lot of different types from other posts and different errors I get from them.

The WHERE clause goes before the GROUP BY:
SELECT rs.pid, rs.title
FROM resources rs JOIN
retags rt
ON rs.pid = rt.pid JOIN
tags t
ON rt.tid = t.id
WHERE rs.title LIKE '%bla%'
GROUP BY rs.pid
HAVING SUM(t.slug = 'tag-z') AND
SUM(t.slug = 'tag-y')
ORDER BY MAX(rs.at);
Strictly speaking, the MAX() is not needed in the ORDER BY assuming that pid uniquely identifies each row in resources.
My guess is that at is in multiple rows, so you need to qualify the reference with the table it comes from. Note that I introduced table aliases so the query is easier to write and to read.

Related

mysql check multiple column in on statement

I am stuck in 1 left join query in which I want to check multiple columns in on statement.
By default in the database, some column is null which I want to check in the on statement.
Now the issue is when I run a query using the OR operator it only runs the 1st condition and the rest are skipped.
If I use AND operator it throws an error.
So is there any way to get data from multiple conditions?
Here is my query:
$data = "SELECT
b.book_name, b.book_id,
b.cats_id, b.cats_id1,
b.cats_id2, b.cats_id3,
b.cats_id4, b.cats_id5,
b.cats_id6,
b.book_rating,
b.book_author,
b.book_stock,
b.book_publisher,
b.book_front_img,
b.book_status,
p.publisher_id,
p.publisher_name,
a.author_id,
a.author_name,
cat.cats_id,
cat.cats_name,
cat.cats_status
FROM
`books` AS b
LEFT JOIN `publisher` AS p
ON b.book_publisher = p.publisher_id
LEFT JOIN `author` AS a
ON b.book_author = a.author_id
LEFT JOIN categorys As cat
ON b.cats_id = cat.cats_id
OR b.cats_id1 = cat.cats_id
OR b.cats_id2 = cat.cats_id
OR b.cats_id3 = cat.cats_id
OR b.cats_id4 = cat.cats_id
OR b.cats_id5 = cat.cats_id
OR b.cats_id6 = cat.cats_id
GROUP BY
b.book_name
HAVING
cat.cats_name = '$search_data'
AND b.book_status = 1
ORDER BY
$sorting
LIMIT $offset, $page_limit"
You probably don't have more than one author displayed for your multi-author books either. You are misusing MySQL's notorious nonstandard extension to GROUP BY.
To troubleshoot this kind of query, disable that extension with SET sql_mode = CONCAT_WS(',',##sql_mode, 'ONLY_FULL_GROUP_BY'), then try your query again. You'll need more terms in your GROUP BY clause.
It looks like each books row has multiple category id columns. And it looks like you want to display information from your categorys table for each of them.
Use GROUP BY b.book_id, p.publisher_id, a.author_id, cats.cats_id to prevent MySQL's bizarro handling of GROUP BY from concealing your data.
I must add this: your multiple books.cats_id columns are not the SQLish way to handle your many-to-many relationship between books and categories. In the parlance of our trade, your books table is denormalized.
What you want is a new table called books_categorys with two columns, book_id and cats_id. It's called a join table. When a row is present in that table, it means a particular book is in a particular category. It's the SQLish way of handling a setup where each book can be in zero or more categorys. Here's an explanation. MySQL join many to many single row
Then you remove all the cats_id columns from books, and retrieve the categories like this.
Then you do something like this SELECT to get the categories.
SELECT books.id, books.name,
categorys.cats_id, categorys.cats_name, categorys.cats_status
FROM books
JOIN books_categorys ON books.book_id = books_categorys.book_id
JOIN categorys ON books_categorys.cats_id = categorys.cats_id
``

Access or Mysql - Table rows as columns in query

I have these three tables:
The table "Clienti" contains the customers.
The table "Corsi" contains all the available courses
The table "corsi Fatti" contains all the Courses each client has taken.
what I would need is a query that returns each client, and what courses he attended on what date.
For that I would like to have for example a table returned with these columns:
Clienti.Nome, corsi.row1.corso, corsi.row2.corso, corsi.row3.corso,corsi.rowN.corso.
and the content of the table should be:
clienti.Nome, corsifatti.data of the matching course in the corsi table if present.
so, first column is the client name, and then there is a column for each row of the "corsi" table, and if a client has partecipated on that course then the corsifatti.data should be in that column.
Can something like this be done with a Access or Mysql Query? I have tried with inner joins but the result was not what I need.
select
Clienti.nome, Clienti.Addresse, Clienti.CAP, Clienti.Tel,
Clienti.Ansprechpartner, Clienti.Mail, Clienti.Weiteres,
CorsiFatti.Data, Corsi.Corso, Corsi.Durata
from Clienti
INNER JOIN CorsiFatti on CorsiFatti.[ID Cliente] = Clienti.ID
INNER JOIN Corsi on Corsi.ID = CorsiFatti.[ID Corso]
What you are asking is a simple inner join:
select Clienti.nome, Clienti.Addresse, Clienti.CAP,
Clienti.Tel, Clienti.Ansprechpartner, Clienti.Mail,
Clienti.Weiteres,
CorsiFatti.Data,
Corsi.Corso, Corsi.Durata
from Clienti
INNER JOIN CorsiFatti on CorsiFatti.[ID Cliente] = Clienti.ID
INNER JOIN Corsi on Corsi.ID = CorsiFatti.[ID Corso]
order by Clienti.nome, Corsi.Corso;
I think you meant yours was lacking the order by only.
I wouldn't suggest using access, but if it is access anyway, then you need to have parenthseses around all those joins (peculiar I know, but it is access).
The pivot with variable columns count is complicated. I can advice simplest solution uses JSON aggregation:
SELECT
ClienteId,
Name,
JSON_ARRAYAGG(
JSON_OBJECT("Data", Data, "Corso", Corso)
) Corsi
FROM
CorsiFatti
JOIN Corsi ON Corsi.Id = CorsiFatti.CorsoId
JOIN Clienti ON Clienti.Id = CorsiFatti.clienteId
GROUP BY
ClienteId,
Name
;
Result is row for each client contains client's data at his courses as JSON string:
+===========+=========+========================================================================================+
| ClienteId | Name | Corsi |
+===========+=========+========================================================================================+
| 1 | Mr. Fix | [{"Data": "2021-01-01", "Corso": "Corso1"}, {"Data": "2021-02-01", "Corso": "Corso3"}] |
+-----------+---------+----------------------------------------------------------------------------------------+
Here you can find SQL fiddle

Mysql: join to include all rows (even where SUM=0)

I have DB with two tables:
rmonth and alternatives
The rmonth is an aggregated table of data for each alternative a complete month - if they have any - otherwise the row don't exist in the rmonth table.
Now I want to join them, and this is my code:
SELECT
COALESCE(rmAntal, 0) AS sumMonth, aID, aText, rmUnitID
FROM
alternatives
LEFT JOIN
rmonth ON aID = rmAltID
WHERE aToQuestID = 4418
AND rmMonth = 3
AND rmYear = 2018
AND rmUnitID IN (10603,10960,10496)
GROUP BY aID, rmUnitID
ORDER BY aID ASC
But it doesn't give me the rows not existing in rmonth.
So this scenario gives me the result as I want it - except that it can't handle where the alternative does not exist for that specific unitID in rmonth.
I want them listed with just 0 in sumMonth.
Unfortunately that's where my MySQL-knowledge is limited.
Thanks.
You could add an OR operator, for example
...
WHERE aToQuestID = 4418 AND rmMonth IS NULL OR (
AND rmMonth = 3
AND rmYear = 2018
AND rmUnitID IN (10603,10960,10496)
)
...
This way, you'll get all your alternatives data, even when it's counter part in rmonth is null.

mysql query select by tag

I have a database with 3 tables with content and i need to get content out of it based on a query of tags.
The tables look like this:
nv_entries:
id - title - year - etc..
nv_tags:
id - entrieid - tag
nv_images:
id - entrieid - source
Let's say i want all entries that have the tag 'rousseau' and both 'fuzz' in it.
After that the images should join aswell where entrieid = entrieid.
This can probably done with one query but i have no idea how.
$query = "SELECT * from nv_entries WHERE ???
please help
Since you have a one to many relationship between entries and tags, you have to use a pivot table on the tags table. Simply saying where tag = 'x" and tag = 'y" won't work because the engine looks at this on a row by row basis so tag can't have both values at the same time. So basically you pivot, assigning flags to each entry that state whether that entry has been seen to have the tag value you're looking for.
SELECT *
FROM nv_entries entries
JOIN (
SELECT entrieid,
COUNT(CASE WHEN (tag = 'rousseau') THEN 1 ELSE null END) has_rousseau,
COUNT(CASE WHEN (tag = 'fuzz') THEN 1 ELSE null END) has_fuzz
FROM nv_tags
GROUP BY entrieid
HAVING has_rousseau != 0 and has_fuzz != 0
) tags ON (entries.id = tags.entrieid)
JOIN nv_images images ON (tags.entrieid = images.entrieid);
SELECT * FROM
nv_entries entries
INNER JOIN nv_tags tags ON tags.entrieid = entries.id
INNER JOIN nv_images imgs ON imgs.entrieid = entries.id
WHERE tags.tag IN('rousseau','fuzz')
but this will extract all data from three tables.
specify your tags relative to the table to avoid redundant tags as entrieid.

MYSQL join with sort and group by choosing the element to display

I have 2 tables, evt and content. content is link to evt throw the column content_evt_fk (to make it simpler, you can replace evt by article and content by comment for a blog database).
What I'm trying to do is to have in one query, the evt id, the evt name, the number of content related to it, and the id and the text of the last inserted content related to this evt.
here is the code :
SELECT
`evt`.`evt_id`,
`evt`.`name`,
`content`.`content_id`,
`content`.`content_text`,
count(*) as `evt_cont`
FROM
`t_evt` as `evt`,
`t_content` AS `content`
WHERE
`evt`.`evt_id` = `content`.`content_evt_fk`
group by `evt_id`
ORDER BY `content`.`content_id` DESC
The issue is that the content_text sent is not the one from the last inserted, but the one for the first inserted row.
I tried tu put some Max() in the query but it didn't helped.
Any clue ?
EDIT : data Sample
let's say I have an evt called "pocket" and 3 related content, inputed in this order ("1-cake","2-chocolate","3-sweets").
The result of my query is
evt_id name content_id content_text evt_cont
149 pocket 112 1-cake 3
What I would like to have :
evt_id name content_id content_text evt_cont
149 pocket 115 3-sweets 3
I'm not working with MySql so there are probably better ways to do this. The simplest way is to join derived table of max (column-representing-order-of-interest, content_id here) by key (content_evt_fk here) to original table filtering out all but last entries.
SELECT
evt.evt_id,
evt.name,
content.content_id,
content.content_text
FROM t_evt as evt
INNER JOIN t_content AS content
ON evt.evt_id = content.content_evt_fk
INNER JOIN
(
select content_evt_fk, max(t_content.content_id) content_id
from t_content
group by content_evt_fk
) last_content
ON content.content_id = last_content.content_id
-- This is not necessary here, but if you do this sort of thing on
-- columns other than id, you will have to join this part too
and content.content_evt_fk = last_content.content_evt_fk