MySQL search with joins and match - php

I've got one table filled with information about companies (tblforetag) in Sweden, one table with provinces (tbllan) and one table with cities (tblstad). The cities are linked to the provinces with id numbers and the company table has a column for the city name (varchar).
How do I search for all the companies in one province?
I have fiddled around with joins but not got it to work. I've got this code right now that works but it will only search for company names and cities (in the company table):
$sql = "
SELECT *,
MATCH(tblforetag.foretag) AGAINST(:keywords) AS kr
FROM tblforetag
WHERE MATCH(tblforetag.foretag) AGAINST(:keywords)
";
$sql .= $locisset ? "AND tblforetag.stad LIKE :location" : "";
$sql .= " LIMIT $offset, $rpp";
$query = $conn->Prepare($sql);
$query->BindValue(':keywords', $keywords);
if($locisset) $query->BindValue(':location', "%$location%");
$query->Execute();

I do not know your table structure but something along these lines shoulod do the trick:
SELECT FROM companies
LEFT JOIN cities ON (companies.city_id = cities.id)
LEFT JOIN regions ON (cities.region_id = regions.id)
WHERE region.name = 'your region'
This would give you the companies in that particular region.

I think it would be better the city_name column in companies table to city_id.
SELECT a.*, p.provincename
FROM companies a, cities c, provinces p
WHERE a.city_name = c.city_name
AND c.city_id = p.city_id
AND p.province_id = 5 // give your province id here

Related

How to place subject scores under each subject in MySQL

I have these tables:
Table that displays the results after I fetched from db:
Result table from the database:
Subjects table from db:
What I am trying to achieve: I want the student identification number appear once and each subject score to appear under the subject just like the image below. How can I go about it in my SQL queries?
My source code:
$sql = "SELECT distinct s.regiNo, s.firstName as fname, s.middleName as mname, s.lastName as lname, s.gender, s.class_group, c.subjects, e.First_CA, e.Second_CA, e.examid, e.scored, e.internaltype, e.Class, e.Year FROM student s, subjects c, exam e WHERE s.regiNo = e.Roll_Number AND e.sub_id = c.subect_code
";
Thanks.
You appears to want conditional aggregation :
select s.regiNo as IdentityNumber, e.Class, s.class_group,
sum(case when c.subect_code = 'math' then (e.First_CA + e.Second_CA + e.scored) else 0 end) as Mathematics,
. . .
from student s inner join
exam e
on s.regiNo = e.Roll_Number inner join
subjects c
on e.sub_id = c.subect_code
group by s.regiNo, e.Class, s.class_group;

how to get count of another table

Like below image I have two tables, now I want to get all columns from Restaurant table depending on cat column, and number of records from Foods table that have that Restaurant id.
example : (to get 1,test from Restaurant table and 3 from Foods table).
$sql = "select * from Restaurant,Foods where cat=6..." ;
updated :
$sql = "r.*,(SELECT COUNT(*) FROM restaurant_foods WHERE restaurant_id = r.id)
foods_count FROM restaurant r WHERE r.cats LIKE '%,$cat,%' limit $start,$end"
That should do the job:
SELECT r.*,
(SELECT Count(*)
FROM Foods
WHERE restaurnat_id = r.id) foods_count
FROM Restaurant r
WHERE r.cat = 6

Echo results of a complicated INNER JOIN query with multiple tables

This is my first question here. I have a complicated SQL database and I need to join different tables which have the same column names.
"event" is a sports match. It contains tournament_stageFK which is linked to tournament_stage table, which contains tournamentFK which is linked to tournament table, which contains tournament_templateFK which is linked to tournament_template table, which contains sportFK which is linked to sport table.
So in order to find out what sport the match is from, I need to do an inner join, otherwise I'd have to open the database millions of times. The only way to do it is this, but I don't know how to display the results. My poor attempt to echo the results is below:
$SQL = "SELECT sport.name,
country.name,
tournament_template.name,
tournament.name,
tournament_stage.name,
event.*
FROM tournament_template
INNER JOIN sport
ON tournament_template.sportFK = sport.id
INNER JOIN tournament ON tournament.tournament_templateFK = tournament_template.id
INNER JOIN tournament_stage ON tournament_stage.tournamentFK = tournament.id
INNER JOIN event ON event.tournament_stageFK = tournament_stage.id
INNER JOIN country ON tournament_stage.countryFK = country.id
WHERE DATE(event.startdate) = CURRENT_DATE()
ORDER BY sport.name ASC,
country.name ASC,
tournament_stage.name ASC,
event.startdate ASC";
$result = mysql_query($SQL);
while($get=mysql_fetch_array($result))
{
echo $result['event.name'];
echo "<br>";
}
Your result is fetched as an array indexed by column name, which is "name" for several of your columns... the table name sport, country, template, etc is not part of the returned index. So you need to provide column names that will be unique
Set an alias for each of your columns (e.g. SELECT sport.name AS sport_name) then reference it by its alias within your echo (e.g. $result['sport_name']).
You need to use column aliases and access those in your fetch call. Instead of event.*, be explicit about the columns you need:
$SQL = "SELECT sport.name AS sportname,
country.name AS countryname,
tournament_template.name AS templatename,
tournament.name AS tournamentname,
tournament_stage.name AS stagename,
/* Use explicit column names instead of event.* */
event.name AS eventname,
event.someothercol AS someother
FROM tournament_template
...etc...
...etc...";
// Later...
while($row=mysql_fetch_array($result))
{
echo $row['eventname'];
echo "<br>";
}

CodeIgniter, Order by number of rows in a separate joined table?

I have 4 tables that link together...
Firstly the hotels table
hotel_id
town_id
hotel_name
Then the towns table:
town_id
region_id
town_name
Then the regions table:
region_id
country_id
region_name
Finally the countries table
country_id
country_name
What I need to do is list the towns in order of how many hotels there are within that town.
The reason I have included the regions table and the countries table is because, when displaying that town, I need to display the country it's from. This can only be obtained via the regions table..
Therefore using the active records in CodeIgniter I have done this so far:
$this->db->join('regions','towns.town_region_id = regions.region_id');
$this->db->join('countries','regions.region_country_id = countries.country_id');
$query = $this->db->get('towns');
foreach ($query->result() as $row) {
echo "<li>";
echo "$row->town_name, $row->country_name";
echo "</li>";
}
This outputs:
London, United Kingdom
Washington, United States
New York, United States
Moscow, Russia
etc, etc
Each one of these cities have hotels in them. All I need now is to order them by how many hotels there are in each town..
Any help would be much appreciated! Thanks.
$this->db->select('t.*,c.*,COUNT(h.hotel_id) AS nhotels');
$this->db->from('towns t');
$this->db->join('hotels h','h.town_id = t.town_id');
$this->db->join('regions r','t.town_region_id = r.region_id');
$this->db->join('countries c','r.region_country_id = c.country_id');
$this->db->group_by('t.town_id');
$this->db->order_by("nhotels",'DESC');
$query = $this->db->get();
which will produce the following query:
SELECT `t`.*, `c`.*, COUNT(h.hotel_id) AS nhotels
FROM (`towns` t)
JOIN `hotels` h
ON `h`.`town_id` = `t`.`town_id`
JOIN `regions` r
ON `t`.`town_region_id` = `r`.`region_id`
JOIN `countries` c
ON `r`.`region_country_id` = `c`.`country_id`
GROUP BY `t`.`town_id`
ORDER BY `nhotels` DESC
SELECT
hotels.town_id,
count(hotels.hotel_id) from hotels AS hotels_count,
towns.town_name
FROM
hotels,
LEFT JOIN
towns ON hotels.town_id = towns.town_id
GROUP BY hotels.town_id
ORDER BY hotels_count DESC;

MySQL: How to store/retrieve artist information?

It's very confusing; it seems like I'll need to have at least one many-to-many relationship.
A track might be sung by 2+ artist - how can I store that in the database?
While showing that track, I want link to each artist so that when users click the track it opens that artist's profile page.
Can anyone provide me with some assistance in designing a class or classes to accomplish this?
Try something like that
tblSongs
SongId
Title
YearProduced
etc.
tblArtist
ArtistId
Name
ProfilePage
etc..
tblSongArtists
SongId
ArtistId
Then your queries could look something like
SELECT Title, YearProduced, Name, ProfilePage
FROM tblSongs S
LEFT OUTER JOIN tblSongArtists SA ON SA.SongId = S.SongId
LEFT OUTER JOIN tblArtists A ON A.ArtistId = SA.ArtistId
WHERE Title = 'I got the blues' -- ....
ORDER BY SongId -- or Song Title (*)
(*) order by clause is in case the search criteria produces more than one song, and if you wish to keep the artists for a given song in sequence.
Such a query produces multiple rows for a song with several artists, one row per artists, the values of the columns from tblSongs being repeated.
Any many-to-many relationship requires three tables. For your example:
Song<br/>
Name SongID
Artist <br/>
Name ArtistID
ArtistsInSongs <br/>
ArtistID SongID
I'll let you figure out the rest.
public static function find_artist_on($track_id=0) {
global $database;
$sql = "SELECT * FROM " . self::$table_name ." s " ;
$sql .= "LEFT OUTER JOIN trackartist TA ON TA.track_id =s.track_id";
$sql .= "LEFT OUTER JOIN artist A ON A.artist_id =TA.artist_id";
$sql .= " WHERE s.artist_id=" .$database->escape_value($track_id);
$sql .= " ORDER BY artist_id ASC";
return self::find_by_sql($sql);
}

Categories