Finding out related data from tables - php

I have three tables in my mysql database which looks like following:
EDIT
The table "members" holds the name and code of some members . Now the table "Boss" contains the name of the member who has been selected as a Boss for an event. Each boss has at least one subordinate (please check the table subordinates).
Now what I am trying to do is find out the names and their points that Bon Jovi (pls check the table table:members) is associated with. When finding out there is a condition... if the "condition_type" from table:boss is 1 then the values from subordinates would be in the right side and if the "condition_type" from table:boss is 0 then the values from subordinates would be in the left side.
Now what I am trying to find out looks like following.

OK i have found a solution for you i am posting
$condition = 1;// Condition will be provided by you for selection. Could be zero
$data = array(
'members.name',
'subordinates.points',
'subordinates.event'
);
$this->db->select($data);
$this->db->join('members','members.code = subordinates.member_code','left');
$this->db->join('boss','boss.event = subordinates.event','left');
$this->db->where('boss.condition_type',$condition);
$this->db->where('boss.event = subordinates.event');
$this->db->get('subordinates');
Also i have event in the selection so that you recognize the difference of events the query will bring. Kindly test and see if it works ok for you. There might be a little difference in the column names. A good approach is to use like this for easy and understandable relationship between tables.
Table1 : members
Columns : id , code , name
Table2 : boss
Columns : id , event , member_code , condition_type
Table3 : subordinates
Columns : id , boss_event , member_code , points

Related

How to retrieve data from table which is separated by comma in sql?

I have table students containing data like given below :
id name activity
1 susan 1,2
2 denny 1,2,3
3 ken 3
I want to choose all the data like name and id from this table having activity equal to 2. I have done a sql query using like but it will not work.
$sqll = mysqli_query($con,"SELECT id,studentname FROM students WHERE activity LIKE '%$activity'");
If another row contains data like id : 4 name:ben activity : 22 it will show this row also. I want the rows containing activity 2 only.
Can anyone suggest a solution for this ?
I agree with the comments so far about normalising the data but to answer your question with the table structure as it is you can do this:
$sqll = mysqli_query($con,"SELECT id,studentname FROM students WHERE CONCAT(',',activity,',') LIKE '%,$activity,%'");
Note, you concatenate a comma either side of the field data and the specific activity you are looking for. Also note, I added a % on the right of the like as well so that "denny" will be caught
SELECT id, studentname
FROM students
WHERE FIND_IN_SET("$activity", activity);

Query selected columns from two tables with a Condition clause

I have two tables-
1) ****Company_Form****
[Contract_No#,Software_Name,Company_Name,Vendor_Code]
2) ****User_Form****
[Contract_No,Invoice_No#,Invoice_Date,Invoice_Amount,Invoice_Submit_Date]
Fields denoted with # and bold are primary keys.
=>The user has to enter a software name for which he wants to get the data of.
=>I have to structure a query in which I have to display the result in the following form:
[Contract#,Software_Name,Company_Name,Invoice_No,Invoice_Date,Invoice_Submission_Date]
Now,
one Contract_No can contain many Invoice_no under its name in
the User Form table.
One Contract_No can occur one time only in
Company_Form table
The retrieved records have to be group by the latest Invoice_Date
I came to the logic that:
I have to first retrieve all the contract numbers with that software
name from Company_Form table.
I have to query that contract number from User_Form table and display
the data for each matched contract no. fetched from Company_Form
table.
The problem is that I am unable to structure a query in SQL that can do the task for me.
Kindly help me in formulating the query.
[PS] I am using SQL with PHP.
I tried a query like:
I tried one approach as :
SELECT a.ContractNo,a.SoftwareName,a.CompanyName,b.InvoiceNo,b.InvoiceDate,b.InvAmount,b.InvoiceSubmitDate
FROM Company_Form as a,User_Form as b
WHERE b.ContractNo IN(SELECT ContractNo FROM Company_Form WHERE
SoftwareName='$Sname') AND a.ContractNo=b.ContractNo;
But I am getting a error that sub query returns more than 1 row.
Can I get help from this?
I am assuming you are attempting to find the most recent price of the user selected software and its corresponding invoice. Here is an approach to do this. If this is tested to your satisfaction, I can add necessary explanation.
select uf.Contract_No#,
cf.Software_Name,
cf.Company_Name,
uf.Invoice_No#,
uf.Invoice_Date,
uf.Invoice_Amount,
uf.Invoice_Submit_Date
from User_Form uf
inner join (
-- Most recent sale of software
select Contract_No#, max(Invoice_Date)
from User_Form
group by Contract_No#
) latest
on (
-- Filter via join for latest match records
uf.Contract_No# = latest.Contract_No#
and uf.Invoice_Date = latest.Invoice_Date
)
inner join Company_Form cf
on cf.Contract_No# = uf.Contract_No#
where cf.Software_name = :software_name
If the requirement allows your sub query to return more than one row, I would suggest you to use IN instead of = in the where clause of your main query.
Please note that I have just looked at the query and have not fully understood the requirements.
Thanks.
I worked around for some time and finally came to the following query which works like a charm
SELECT a.ContractNo,a.SoftwareName,a.CompanyName,b.InvoiceNo,b.InvoiceDate,b.InvAmount,b.ISD
FROM Company_Form as a,User_Form as b
WHERE b.ContractNo IN (SELECT ContractNo FROM Company_Form WHERE SoftwareName='$Sname')
AND a.ContractNo=b.ContractNo;
If anybody needs help in understanding the logic of this query,feel free to comment below.

joining two mysql tables without unique common field

I made a big mistake in inserting data from my survey application and now I really stuck! I have list of movies in my table "featuredfilms_EN" with these fields: movieName, ImdbId(unique Id of movies), year. In my survey app, I asked users about their favorite movies and I stored their answers in the "Answer_CROWD" table which has these fields: qId, answer.
Now I faced a big problem that is: I need to join these two tables, but since I forgot to store the unique_Id(ImdbId) in "Answer_CROWD" table, I cannot!:(
I appreciate if someone can help me if there is a way that I can join these two tables? I am really stuck... I have a deadline tomorrow and I just found this big issue now.
it looks like you could concat the movieName & year & match on that
SELECT * FROM featuredfilms_EN
JOIN Answer_CROWD ON lower(answer)=lower(concat(trim(movieName), '_', year))
I write here because in comment will be confused,
now i can't see fields of tables so i write generic but i'think you understand:
update query:
1 add a field called for example Film_id to Answer_CROWD
2 select id,concat(trim(movieName), '_', year) as title from Featuredfilms_EN and put in $rows
3 in a
`foreach ($rows as $value ){
$id=$value['id'];
$title=$value['title'];
$sql="UPDATE Answer_CROWD SET Film_id='$id' WHERE lower(answer)=lower('$title')";
....do query
}`

changing during accomplish query

I've such a interested question for me , please if anyone know answer me .
So I have two table , in first i have column named "num" which includes (like say phone numbers) and in second table i have column "sec_num" which also includes some of the exactly same numbers like in first table from column "num" and second column named "persons" (from second table also)
I am retrieving data from first table and i want that if first table phone numbers (from num column) matched to second table numbers (from column "sec_num") then retrieved value from "persons" column. Is it possible to do ? if yes , please help me , Thanks ...
PS. if it is necessary to know i am using php, but I think this job must do sql
If I understand the question right a regular left join should do the trick;
select num, persons from first left join second on num=sec_num;
If we call the tables tableA (first table) and tableB (second table) thern a query like:
SELECT * FROM tableA INNER JOIN tableB on tableA.num = tableB.sec_num
should do the trick.

Retrieving Data from a field with comma delimitation SQL

I have a publications database and I need to fetch some information regarding the author. The author field is such that the authors have been lumped together in one field e.g if a book has two authors called Robert Ludlum and John Grisham, in the database it is saved as Ludlum, R.;Grisham,J.;
My application needs to spool information and retrieve data on books authored by a particular author if they click on their name. I am using this statement to retrieve the data
$select = "SELECT tblPublications.Title, tblPublications.Year FROM tblPublications WHERE tblPublications.Authors LIKE '%$sname%'";
$sname is a variable referring to the surname of the author. The problem arises if two authors share the same surname. however a workaround I am trying to implement is to get the applicationtake the surname, insert a comma, take the first name of a user and get the first letter then combine the result to a stringe and match them to each comma delimited value in the author field e.g if it is Grisham's books I am looking for I use *Grisham, J.* in my query.
Any Idea how to do this in PHP,MYSQL?
If it is possible to redesign the database, you should probably have an authors table and a book_authors table that relates books to authors, so that multiple authors can be associated with each book. Where is the Last Name coming from that the user clicks? Is it possible to have the link generated be LastName, First letter of first name? If so then you can probably change the link so it will include the first letter. But it is still possible to have two authors with the same last name and first letter of first name. So I think the best solution is to have an authors table and a Book_authors table and just store the author id as a hidden field and use that to retrieve the books by the selected author.
Your database design is incorrect, you have not normalized the data.
If you use like to search with leading wildcards, you will kill any chance of using an index.
Your only option to fix (if you want to keep the mistaken CSV data) is to convert the table to MyISAM format and put a FULLTEXT index on the authors field.
You can then search for an author using
SELECT fielda, b,c FROM table1 WHERE MATCH(authors) against ('$lastname')
See: http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
Of course a better option would be to normalize the database and create a separate table for authors with a link table.
TABLE books
------------
id primary key
other book data
TABLE authors
--------------
id primary key
lastname varchar (indexed)
other author data
TABLE author_book_link
----------------------
author_id
book_id
PRIMARY KEY ab (author_id, book_id)
Now you can query using very fast indexes using something like:
SELECT b.name, b.ISBN, a.name
FROM books b
INNER JOIN author_book_link ab ON (ab.book_id = b.id)
INNER JOIN author a ON (a.id = ab.author_id)
WHERE a.lastname = '$lastname'
It would entirely depend on what input you are getting from the user.
If the user just types a name, then there isn't much you can do (as there is no guarantee that they will enter it in a correct format for you to parse).
If you are getting them to type in a firstname and lastname however, something like this could be done:
<?php
$firstname = trim(mysql_real_escape_string($_GET['fname']));
$surname = trim(mysql_real_escape_string($_GET['sname']));
$firstletter = substr($_GET['fname'],0,1);
$sname = $surname.', '.$firstletter;
$select = "SELECT tblPublications.Title,
tblPublications.Year
FROM tblPublications
WHERE tblPublications.Authors LIKE '%$sname%'";

Categories